package net.seabook.games.tetris.ui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;

import net.seabook.games.tetris.model.Piece;
import net.seabook.games.tetris.model.PieceGenerator;
import net.seabook.games.tetris.model.TetrisBoard;
import net.seabook.games.tetris.model.Tile;

public class PreviewPanel extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3679216379470728624L;
	
	private static final int WIDTH = 3 * TetrisBoard.BOARD_WIDTH / 5;
	private static final int HEIGHT = 2 * TetrisBoard.BOARD_HEIGHT / 5;
	
	private static final int PREVIEW_BLOCK_WIDTH = 5 * Tile.WIDTH;
	private static final int PREVIEW_BLOCK_HEIGHT = 5 * Tile.HEIGHT;
	
	public static final int PREVIEW_BLOCK_ORG_X = Tile.WIDTH / 2;
		//TetrisBoard.BOARD_WIDTH + Tile.WIDTH;
	public static final int PREVIEW_BLOCK_ORG_Y = 3 * Tile.HEIGHT;
		//TetrisBoard.BOARD_HEIGHT + 2 * Tile.HEIGHT;
	
	private Piece piece = null;
	
	private PieceGenerator generator;
	
	private Timer timer;
	
	private SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
		@Override
		protected Void doInBackground() throws Exception {
			while (true) {
				Thread.sleep(50);
				if (generator != null)
					piece = generator.getPreviewPiece();
				System.out.println(piece.getClass().getSimpleName());
				repaint();
			}
		}
		
	};

	public PreviewPanel(Piece piece) {
		this.piece = piece;
		timer = new Timer(100, this);
		timer.start();
	}
	
	@Override
	public Dimension getPreferredSize() {
		return new Dimension(WIDTH, HEIGHT);
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawRect(PREVIEW_BLOCK_ORG_X, PREVIEW_BLOCK_ORG_Y, PREVIEW_BLOCK_WIDTH , PREVIEW_BLOCK_HEIGHT);
		piece.drawSelf(g);
	}
	
	public Piece getPiece() {
		return piece;
	}

	public void setPiece(Piece piece) {
		this.piece = piece;
	}

	public PieceGenerator getGenerator() {
		return generator;
	}

	public void setGenerator(PieceGenerator generator) {
		this.generator = generator;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (generator != null)
			piece = generator.getPreviewPiece();
		repaint();
	}
}
